package com.showsu.editor.utils;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.showsu.editor.entity.platform.xhs.AwemeDetailPlatformResult;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Semaphore;

/**
 * @Author: William
 * @Description: 第三方平台接口请求计数器，用于统一控制请求到某个第三方平台接口的频率，目的是提高单次的成功率。目前只有极少数的接口用到
 * @Date: Created in 6:57 下午 2024/7/30
 * @Modified By:
 */
@Slf4j
public class RemotePlatformRequestRateLimiter {

    private static final Semaphore semaphore = new Semaphore(1);
    private static volatile long lastRequestTime = System.currentTimeMillis();

    /**
     * 用计数器发起get请求，目前仅用于xhs笔记详情页接口
     * @param urlString get请求的url
     * @param timeout get请求的timeout限制
     * @param rate 允许的间隔时长，单位是1毫秒
     * @return
     */
    public String sendGetRequestAndReturnXhsAwemeDetailPlatformResultString(String urlString, int timeout, long rate) {
        String result = "";
        try {
            if (semaphore.getQueueLength() > 3) {
                log.error("semaphore队列过长 队列长度" + semaphore.getQueueLength());
                AwemeDetailPlatformResult result1 = new AwemeDetailPlatformResult();
                result1.setCode(103);
                result1.setMsg(Constant.batmkeyPrivaterRteLimiterMsg);
                result1.setStatus_code(200);
                return JSON.toJSONString(result1);
            }
            // 等待直到可以发送请求
            semaphore.acquire(1);
            long currentTime = System.currentTimeMillis();
            long currentTimeRate = currentTime - lastRequestTime;
            if (currentTimeRate > 0 && currentTimeRate < rate) {
                long waitTime = rate - currentTimeRate;
                if (waitTime > 0) {
                    Thread.sleep(waitTime);
                }
            }
            result = HttpUtil.get(urlString, timeout);
            lastRequestTime = System.currentTimeMillis();
        } catch (Exception e) {
            log.error("RemotePlatformRequestRateLimiter.sendGetRequest(String, int, long) error", e);
        } finally {
            semaphore.release(1);
        }
        return result;
    }
}
